package com.mybatis.moudles.apiproject.utils;

import okhttp3.*;

import java.io.IOException;

public class HttpUtils {
    public static String get(String url){
        OkHttpClient client =new OkHttpClient();
        Request request =new Request.Builder().url(url).get().build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            System.out.println(response.code());
            System.out.println(response.headers());
            String body =response.body().string();
            System.out.println(body);
            return body;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String get(String url,String params){
        OkHttpClient client =new OkHttpClient();
        Request request =new Request.Builder().url(url+"?"+params).get().build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            System.out.println(response.code());
            System.out.println(response.headers());
            String body =response.body().string();
            System.out.println(body);
            return body;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String post(String url,String params){

        OkHttpClient client =new OkHttpClient();
        MediaType type = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body =RequestBody.create(type,params);

        Request request =new Request.Builder().url(url).post(body).addHeader("Cookie","connect.sid=s%3As9zm-7f_pI-QHeO2heAPdyeOkJzAjoLl.4fFQcCGJZOYemxAwDWGfKE%2B81OByheWkKyrwGPvsj5k").build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            System.out.println(response.code());
            System.out.println(response.headers());
            String body1 =response.body().string();
            System.out.println(body1);
            return body1;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String call(String method,String url ,String params){
        if("get".equalsIgnoreCase(method)){
            if(params ==""){
                return get(url);
            }else{
                return get(url,params);
            }

        }else if ("post".equalsIgnoreCase(method)){
           return post(url,params);
        }
        return null;
    }


}
